package com.example.saveword.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.saveword.model.User;
import com.example.saveword.model.StudyRecord;
import com.example.saveword.utils.JsonUtils;
import com.example.saveword.utils.SPUtils;
import com.example.saveword.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@SuppressLint("Range")
public class StudyRecordDao {
    private DBOpenHelper helper;
    private SQLiteDatabase db;
    private final Context context;
    User user;
    WordRecordDao wordRecordDao;
    public StudyRecordDao(Context context){
        this.context=context;
        wordRecordDao = new WordRecordDao(context);
        user = (User) JsonUtils.jsonToObject((String) SPUtils.get(context, "User", ""), User.class);
    }
    //添加方法
    public void add(StudyRecord studyRecord){
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();

        ContentValues values=new ContentValues();
        values.put("date", studyRecord.getDate());
        values.put("newNum", studyRecord.getNewNum());
        values.put("repeatNum", studyRecord.getRepeatNum());
        values.put("needNewNum", studyRecord.getNeedNewNum());
        values.put("needRepeatNum", studyRecord.getNeedRepeatNum());
        values.put("difficulty", studyRecord.getDifficulty());
        values.put("user_id", studyRecord.getUserID());
        db.insert("tb_studyrecord",null,values);
        //关闭数据库
        db.close();
        helper.close();
    }
    //更新方法
    public void update(StudyRecord studyRecord){
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();

        ContentValues values=new ContentValues();
        values.put("date", studyRecord.getDate());
        values.put("newNum", studyRecord.getNewNum());
        values.put("repeatNum", studyRecord.getRepeatNum());
        values.put("needNewNum", studyRecord.getNeedNewNum());
        values.put("needRepeatNum", studyRecord.getNeedRepeatNum());
        values.put("learnTime", studyRecord.getLearnTime());
        db.update("tb_studyrecord",values,"_id=?",new String[]{String.valueOf(studyRecord.get_id())});
        //关闭数据库
        db.close();
        helper.close();
    }
    // 返回当前用户的在本词书已背的全部单词的数量
    @SuppressLint("Recycle")
    public Integer getStudyCount(String wordType)
    {
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();

        int id = user.get_id();
        String sql = "select sum(newNum) from tb_studyrecord where user_id = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{String.valueOf(id)});
        if (cursor.moveToNext()){
            int ans = cursor.getInt(cursor.getColumnIndex("sum(newNum)"));
            cursor.close();
            db.close();
            helper.close();
            return ans;
        }
        cursor.close();
        db.close();
        helper.close();
        return 0;
    }
    //插入或者返回方法,若有今天数据就返回，没有就新建
    public StudyRecord addOrGet(){
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        final Calendar c=Calendar.getInstance();//获取系统当前数据
        int year=c.get(Calendar.YEAR);
        int month=c.get(Calendar.MONTH) + 1;
        int day=c.get(Calendar.DAY_OF_MONTH);
        String date0;
        if(day <= 9) date0 = year+"-"+month+"-0"+day;
        else date0 = year+"-"+month+"-"+day;
        String wordType= user.getWordType();
        String sql="select * from tb_studyrecord where date=? and difficulty= ? and user_id = ?";
        Cursor cursor=db.rawQuery(sql,new String[]{date0, wordType, String.valueOf(user.get_id())});
        StudyRecord studyRecord;
        if (cursor.moveToNext()){
            int _id=cursor.getInt(cursor.getColumnIndex("_id"));
            String date=cursor.getString(cursor.getColumnIndex("date"));
            int newNum=cursor.getInt(cursor.getColumnIndex("newNum"));
            int repeatNum=cursor.getInt(cursor.getColumnIndex("repeatNum"));
            int needNewNum=cursor.getInt(cursor.getColumnIndex("needNewNum"));
            int needRepeatNum=cursor.getInt(cursor.getColumnIndex("needRepeatNum"));
            int learnTime = cursor.getInt(cursor.getColumnIndex("learnTime"));
            int user_id = user.get_id();
            studyRecord = new StudyRecord(_id, date, newNum, repeatNum, needNewNum, needRepeatNum, wordType ,user_id, learnTime);
            cursor.close();
            db.close();
            helper.close();
        }else {
            //没有就insert
            int newNum = 0;
            int repeatNum = 0;
            int needNewNum = getNeedNewNum();
            int needRepeatNum = wordRecordDao.findNeedReview().size();
            studyRecord = new StudyRecord(-1, TimeUtils.getDateStr(new Date(), null), newNum, repeatNum, needNewNum, needRepeatNum, user.getWordType(), user.get_id(), 0);
            add(studyRecord);
        }
        return studyRecord;
    }

    //返回最近的count条数据
    public ArrayList<StudyRecord> getCountRecord(int count){
        ArrayList<StudyRecord> studyRecord_list =new ArrayList<StudyRecord>();
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        String wordType=user.getWordType();
        String sql="select * from tb_studyrecord  where difficulty=? order by datetime(date) DESC limit ? ";
        Cursor cursor=db.rawQuery(sql,new String[]{wordType, String.valueOf(count)});
        while (cursor.moveToNext()){
            int _id=cursor.getInt(cursor.getColumnIndex("_id"));
            String date=cursor.getString(cursor.getColumnIndex("date"));
            int newNum=cursor.getInt(cursor.getColumnIndex("newNum"));
            int repeatNum=cursor.getInt(cursor.getColumnIndex("repeatNum"));
            int needNewNum=cursor.getInt(cursor.getColumnIndex("needNewNum"));
            int needRepeatNum=cursor.getInt(cursor.getColumnIndex("needRepeatNum"));
            int learnTime = cursor.getInt(cursor.getColumnIndex("learnTime"));
            StudyRecord studyRecord =new StudyRecord(_id,date,newNum,repeatNum,needNewNum,needRepeatNum,wordType, user.get_id(), learnTime);
            studyRecord_list.add(studyRecord);
        }
        cursor.close();
        db.close();
        helper.close();
        Collections.reverse(studyRecord_list);//对数据进行翻转，将今天放在最后
        return studyRecord_list;
    }
    // 返回用户本词书今天需要学习的个数
    public int getNeedNewNum()
    {
        ArrayList<StudyRecord> studyRecord_list = getCountRecord(1);
        if(studyRecord_list.isEmpty()) return 5;
        else return studyRecord_list.get(0).getNeedNewNum();
    }
    //返回总共学习的天数
    public int getAllStudyDayCount(){
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();

        String sql="select count(Distinct date) from tb_studyrecord";
        Cursor cursor=db.rawQuery(sql,null);
        if (cursor.moveToNext()){
            int count= cursor.getInt(0);
            //关闭游标和数据库
            cursor.close();
            db.close();
            helper.close();
            return count;
        }
        return 0;
    }

    //更新今天已经背的单词数
    public void updatefirstNum(){
        StudyRecord studyRecord = addOrGet();
        studyRecord.setNewNum(studyRecord.getNewNum()+1);
        update(studyRecord);
    }
    //更新今天已经复习的单词数
    public void updatereviewNum(){
        StudyRecord studyRecord =addOrGet();
        studyRecord.setRepeatNum(studyRecord.getRepeatNum()+1);
        update(studyRecord);
    }

    // 获取用户共学习的某一级别的单词量
    public int getLearningWordByIdAndType(String id, String type) {
        helper = new DBOpenHelper(context);
        db = helper.getReadableDatabase();
        String sql = "select sum(newNum) from tb_studyrecord where user_id = ? and difficulty = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{id, type});
        int num = 0;
        if(cursor.moveToNext()) {
            num = cursor.getInt(cursor.getColumnIndex("sum(newNum)"));
        }
        cursor.close();
        db.close();
        helper.close();
        return num;
    }

    // 获取用户某一天的已学习单词量
    public String getStudiedByDay(String id, String date) {
        helper = new DBOpenHelper(context);
        db = helper.getReadableDatabase();
        String sql = "select * from tb_studyrecord where user_id = ? and date = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{id, date});
        int num = 0;
        if(cursor.moveToNext()) {
            num = cursor.getInt(cursor.getColumnIndex("newNum"));
        }
        cursor.close();
        db.close();
        helper.close();
        return String.valueOf(num);
    }

    // 获取用户某一天的已复习单词量
    public String getRepeatedByDay(String id, String date) {
        helper = new DBOpenHelper(context);
        db = helper.getReadableDatabase();
        String sql = "select * from tb_studyrecord where user_id = ? and date = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{id, date});
        int num = 0;
        if(cursor.moveToNext()) {
            num = cursor.getInt(cursor.getColumnIndex("repeatNum"));
        }
        cursor.close();
        db.close();
        helper.close();
        return String.valueOf(num);
    }

    // 获取所有打了卡的日期
    public List<String> getAllChecked(String id) {
        helper = new DBOpenHelper(context);
        db = helper.getReadableDatabase();
        String sql = "select * from tb_studyrecord where user_id = ? and learnTime >= 20";
        Cursor cursor = db.rawQuery(sql, new String[]{id});
        List<String> res = new ArrayList<>();
        while(cursor.moveToNext()) {
            String date = cursor.getString(cursor.getColumnIndex("date"));
            res.add(date);
        }
        cursor.close();
        db.close();
        helper.close();
        return res;
    }
}
